from collections import OrderedDict
import os
from datetime import datetime

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from django.conf import settings
from apps import redis_client
from .serializer import *
from .models import *
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError


class MFileViewSet(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="list")
    def mlist(self, requests, *args, **kwargs):
        filename = requests.GET.get("filename")
        filetype = requests.GET.get("filetype")
        if not filetype:
            filetype = None
        data = {"filename": filename, "filetype": filetype}
        serializers = FileListCheckSerializer(data=data)
        if serializers.is_valid():
            mfiles = MFileModel.objects
            file_name = serializers.validated_data.get("filename")
            file_type = serializers.validated_data.get("filetype")
            if file_name:
                mfiles = mfiles.filter(filename__icontains=file_name)
            if file_type:
                mfiles = mfiles.filter(filetype=file_type)
            mfiles = mfiles.order_by("-create_date")
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=mfiles, request=requests, view=self)
            mfiles_re = FileListSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, mfiles_re.data))
        else:
            raise ValidationError(20001)

    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas)
        ])
        return a

    @action(detail=False, methods=["POST", ], url_path="create")
    def mcreate(self, requests, *args, **kwargs):
        serializer = mfileSerializer(data=self.request.data)
        if serializer.is_valid():
            key = serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "成功", "key": key})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="remove")
    def mremove(self, requests, *args, **kwargs):
        key = self.request.data.get("id")
        serializer = MfileUpdateSerializer(data={"key": key})
        if serializer.is_valid():
            key = serializer.update(serializer.validated_data)
            return Response({"code": 200, "msg": "删除成功", "key": key})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="fileupload")
    def mupload(self, requests, *args, **kwargs):
        key = self.request.data.get("fileid")
        mfile = MFileModel.objects.filter(id=key).first()
        filepath = mfile.filepath
        misssion = Mission.objects.filter(file_path=filepath, state=0).first()
        if misssion:
            raise ValidationError(12004)
        file_path = mfile.filepath
        file_name = mfile.filename
        mfile.is_exist = True
        mfile.create_date = now()
        mfile.save()
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        destination = open(file_path, "wb+")
        for chunk in myFile.chunks():
            destination.write(chunk)
        destination.close()
        return Response({
            "code": 200,
            "msg": "上传成功"
        })

    @action(detail=False, methods=["GET", ], url_path="mupdatelist")
    def mupdatelist(self, requests, *args, **kwargs):
        filename = requests.GET.get("filename")
        filetype = requests.GET.get("filetype")
        if not filetype:
            filetype = None
        data = {"filename": filename, "filetype": filetype}
        serializers = FileListCheckSerializer(data=data)
        if serializers.is_valid():
            mfiles = MFileModel.objects.filter(is_exist=True)
            file_name = serializers.validated_data.get("filename")
            file_type = serializers.validated_data.get("filetype")
            if file_name:
                mfiles = mfiles.filter(filename__icontains=file_name)
            if file_type:
                mfiles = mfiles.filter(filetype=file_type)
            mfiles = mfiles.order_by("-create_date")
            results = []
            for mfile in mfiles:
                results.append({
                    "key": mfile.filename,
                    "name": mfile.filename,
                    "id": mfile.id
                })
            return Response({
                "code": 200,
                "result": results
            })
        else:
            raise ValidationError(20001)
